﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace NETCORE.TASKRORD.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class TestController : ControllerBase
    {
        public TestController() { }

        /// <summary>
        /// 最简单的使用方式
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTask")]
        public IActionResult GetTask()
        {
            Console.ForegroundColor = ConsoleColor.Red;

            // 执行一个无返回值的任务
            Task.Run(() => { Console.WriteLine("runing ..."); });

            // 执行一个返回 int 类型结果的任务
            var res1 = Task.Run<int>(() => { return 483; });

            // 声明一个任务，仅声明，不执行
            Task t = new Task(() => { Console.WriteLine("声明"); });

            Console.ResetColor();

            return Ok("test");
        }

        /// <summary>
        /// 使用 TaskFactory 工厂开始异步任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTask2")]
        public IActionResult GetTask2()
        {
            Console.ForegroundColor = ConsoleColor.Red;

            List<Task<int>> tasks = new List<Task<int>>();

            TaskFactory factory = new TaskFactory();

            tasks.Add(factory.StartNew<int>(() => { Console.WriteLine("t1"); return 1; }));
            tasks.Add(factory.StartNew<int>(() => { Console.WriteLine("t2"); return 2; }));
            tasks.Add(factory.StartNew<int>(() => { Console.WriteLine("t3"); return 3; }));

            tasks.ForEach(t => Console.WriteLine("Task:{0}", t.Result));

            Console.ResetColor();

            return Ok("test2");
        }


        /// <summary>
        ///  处理 Task 中的异常
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTask3")]
        public IActionResult GetTask3()
        {
            Console.ForegroundColor = ConsoleColor.Red;

            var task = Task.Run(() =>
            {
                Console.WriteLine("SimpleTask");
                Task.Delay(1000).Wait();
                throw new Exception("SimpleTask Error");
            });

            try
            {
                task.Wait();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }

            if (task.IsCompletedSuccessfully)//任务成功
            {
                Console.WriteLine("IsCompletedSuccessfully");
            }

            if (task.IsCompleted)//任务完成
            {
                Console.WriteLine("IsCompleted");
            }


            Console.ResetColor();

            return Ok("test2");
        }


        /// <summary>
        /// 获取当前线程上下文对象
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTask4")]
        public IActionResult GetTask4()
        {
            Console.ForegroundColor = ConsoleColor.Red;

            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            var UISyncContext = TaskScheduler.FromCurrentSynchronizationContext();

            var t1 = Task.Factory.StartNew(() => { return 1; });

            t1.ContinueWith((atnt) => { Console.WriteLine("从这里访问 UI 线程的资源"); }, UISyncContext);

            Console.ResetColor();

            return Ok("test2");
        }


        /// <summary>
        ///基于 ThreadPool 线程池的方式
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTask5")]
        public IActionResult GetTask5()
        {
            Console.ForegroundColor = ConsoleColor.Red;

            var available = ThreadPool.SetMaxThreads(8, 16);
            Console.WriteLine("result:{0}", available);

            Console.ResetColor();

            return Ok("test2");
        }



        /// <summary>
        /// 长时间运行于后台的任务
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTask6")]
        public IActionResult GetTask6()
        {
            Console.ForegroundColor = ConsoleColor.Red;

            Task.Factory.StartNew(() => { Console.WriteLine("LongRunging Task"); }, TaskCreationOptions.LongRunning);
            Console.ResetColor();

            return Ok("test2");
        }



        /// <summary>
        /// 有条件的 Task
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Route("GetTask7")]
        public IActionResult GetTask7()
        {
            Console.ForegroundColor = ConsoleColor.Red;

            //var order1 = Task.Run<string>(() => { Console.WriteLine("Order 1 "); return "order1 result"; });

            //// 匿名委托将等待 order1 执行完成后执行，并将 order1 对象作为参数传入
            //order1.ContinueWith((task) => { Console.WriteLine("order1 is completed! {0}", task.Result); });

            //var t1 = Task.Run(() => { Task.Delay(1500).Wait(); Console.WriteLine("t1"); });
            //var t2 = Task.Run(() => { Task.Delay(2000).Wait(); Console.WriteLine("t2"); });
            //var t3 = Task.Run(() => { Task.Delay(3000).Wait(); Console.WriteLine("t3"); });

            //Task.WaitAll(t1, t2, t3);

            //// t1,t2,t3 完成后输出下面的消息
            //Console.WriteLine("t1,t2,t3 Is Complete");

            //var t4 = Task.Run(() => { Task.Delay(1500).Wait(); Console.WriteLine("t4"); });
            //var t5 = Task.Run(() => { Task.Delay(2000).Wait(); Console.WriteLine("t5"); });
            //var t6 = Task.Run(() => { Task.Delay(3000).Wait(); Console.WriteLine("t6"); });
            //Task.WaitAny(t4, t5, t6);
            //// 当任意任务完成时，输出下面的消息，目前按延迟时间计算，在 t4 完成后立即输出下面的信息
            //Console.WriteLine("t4,t5,t6 Is Complete");

            //var t7 = Task.Run(() => { Task.Delay(1500).Wait(); Console.WriteLine("t7"); });
            //var t8 = Task.Run(() => { Task.Delay(2000).Wait(); Console.WriteLine("t8"); });
            //var t9 = Task.Run(() => { Task.Delay(3000).Wait(); Console.WriteLine("t9"); });
            //var whenAll = Task.WhenAll(t7, t8, t9);
            //// WhenAll 不会等待，所以这里必须显示指定等待
            //whenAll.Wait();
            //// 当所有任务完成时，输出下面的消息
            //Console.WriteLine("t7,t8,t9 Is Complete");

            var t10 = Task.Run(() => { Task.Delay(1500).Wait(); Console.WriteLine("t10"); });
            var t11 = Task.Run(() => { Task.Delay(2000).Wait(); Console.WriteLine("t11"); });
            var t12 = Task.Run(() => { Task.Delay(3000).Wait(); Console.WriteLine("t12"); });
            var whenAny = Task.WhenAll(t10, t11, t12);
            // whenAny 不会等待，所以这里必须显示指定等待
            whenAny.Wait();
            // 当任意任务完成时，输出下面的消息，目前按延迟时间计算，在 t10 完成后立即输出下面的信息
            Console.WriteLine("t10,t11,t12 Is Complete");

            Console.ResetColor();

            return Ok("test2");
        }

    }
}
